package com.lizx.framework.web.smart.framework.core.helper;

import com.lizx.framework.web.smart.framework.core.utils.SmartReflectionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * bean容器
 *
 * @Author: lizx
 * @Description:
 * @Date: Create in 2019/1/18 9:09 AM
 */
public class SmartBeanHelper {
    private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<>();

    /**
     * 设置bean类与实例的映射关系
     */
    static {
        Set<Class<?>> beanClassSet = SmartClassHelper.getBeanClassSet();
        for (Class<?> beanClass : beanClassSet) {
            Object obj = SmartReflectionUtil.newInstance(beanClass);
            BEAN_MAP.put(beanClass, obj);
        }
    }

    /**
     * 获取bean映射
     * @return
     */
    public static Map<Class<?>,Object> getBeanMap(){
        return BEAN_MAP;
    }

    /**
     * 获取bean实例
     * @param cls
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> cls){
        if (!BEAN_MAP.containsKey(cls)){
            throw  new RuntimeException("无法获取"+cls.getName()+"的实例");
        }
        return (T) BEAN_MAP.get(cls);
    }
}
